package com.gudaomai.wuye.web;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;

import java.util.List;


import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.gudaomai.wuye.common.CommonConstant;
import com.gudaomai.wuye.common.CommonException;
import com.gudaomai.wuye.common.MsgConstant;
import com.gudaomai.wuye.entity.Charge;
import com.gudaomai.wuye.entity.ChargeInput;
import com.gudaomai.wuye.entity.ChargeItemDetail;
import com.gudaomai.wuye.entity.House;
import com.gudaomai.wuye.entity.HouseOwner;
import com.gudaomai.wuye.entity.Park;
import com.gudaomai.wuye.entity.RetEntity;
import com.gudaomai.wuye.service.IChargeItemDetailServ;
import com.gudaomai.wuye.service.IChargeServ;
import com.gudaomai.wuye.service.IHouseOwnerServ;
import com.gudaomai.wuye.service.IHouseServ;
import com.gudaomai.wuye.service.IParkServ;


import org.springframework.web.bind.annotation.RequestParam;

import com.gudaomai.wuye.web.BaseController;


import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zenghualu
 * @since 2017-08-18
 */
@Api(description="收费项目操作")
@Controller
@RequestMapping("/wuye/charge")
public class ChargeCtrl extends BaseController {

	@Autowired
	IChargeServ chargeService;
	@Autowired
	IHouseServ houseService;
	@Autowired
	IParkServ parkService;
	@Autowired
	IChargeItemDetailServ chargeItemDetailService;
	@Autowired
	IHouseOwnerServ houseOwnerService;
	/**
	 * 添加一个新的收费项目
	 * 1.校验收费项目
	 * 2.检测数据库是否存在该收费项目
	 * 3.存在，抛出异常
	 * 4.不存在，进行添加操作
	 * @param charge
	 * @return
	 */
	@ApiOperation("收费项目设置画面，添加收费项目")
	@RequestMapping(value="/",method=RequestMethod.POST)
	public RetEntity addCharge(@RequestBody @Validated Charge charge){
		
		return null;
	}
	
	/**
	 * 根据id删除收费项目
	 * 1.执行删除操作
	 * @param id
	 * @return
	 */
	@ApiOperation("收费项目设置画面，根据_id删除收费项目")
	@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
	public RetEntity deleteCharge(@PathVariable("id")int id){
		
		return null;
	}
	
	/**
	 * 根据查询条件获取收费项目
	 * 条件：包括页面数和记录数
	 * @param charge
	 * @return
	 */
	@ApiOperation("收费项目设置画面，查询收费项目")
	@RequestMapping(value = "/", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getCharge(@RequestBody Charge charge){
		
		return null;
	}
	
	/**
	 * 获取非计划型收费的信息 
	 * 1.默认参数：cf_valuation_type='非计划收费'
	 * @return
	 */
	@ApiOperation("收费项目设置画面，获取非计划收费项目")
	@RequestMapping(value = "/nonPlanCharge", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getNonPlanCharge() {

		return null;
	}

	/**
	 * 根据车位编号获取收费信息
	 * 1.
	 * @param parkCode
	 * @return
	 */
	@ApiOperation("收费项目设置画面，根据车位编号获取收费项目")
	@RequestMapping(value = "/parkCode", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getChargeByParkCode(@RequestParam("parkCode") String parkCode) {

		return null;
	}
	
	/**
	 * 获取所有计划收费项目
	 * 1.默认参数：cf_valuation_type='计划收费'
	 * @return
	 */
	@ApiOperation("收费项目设置画面，获取计划收费项目")
	@RequestMapping(value = "/planCharge", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getPlanCharge() {

		return null;
	}
	
	/**
	 * 获取所有优惠收费项目
	 * 1.默认参数：cf_valuation_type='定向优惠'
	 * @return
	 */
	@ApiOperation("收费项目设置画面，获取定向优惠收费项目")
	@RequestMapping(value = "/discountCharge", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getDiscountCharge() {

		return null;
	}
	
	/**
	 * 获取所有退费收费项目
	 * 1.默认参数：cf_valuation_type='退费项目'
	 * @return
	 */
	@ApiOperation("收费项目设置画面，获取退费项目")
	@RequestMapping(value = "/refundCharge", method = RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Charge> getRefundCharge() {

		return null;
	}
	
	/** 
	 * add a new charge
	 * 
	 * 1. Check if all required field are filled in.
	 * 2. Check if all the inputs are valid.
	 * 3. Check if the charge with the same properties does not exist in the DB.
	 * 4. Save the inputed values.
	 * 
	 *@param  
	 *@author jess
	 *@author xiao
	 *return 
	 *
	 **/
	
	@ApiOperation("费用设置页面，点击添加按钮时，添加费用设置")
	@RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public RetEntity addCharge(@RequestBody ChargeInput chargeInput) throws CommonException {
		
		RetEntity entity = new RetEntity();
		
	  if(chargeService.isExist(chargeInput.getTitle())){
		  //The charge already exists in the database
		  
		  throw new CommonException(CommonConstant.RESULT_CODE_CREATED, 
					getMessage(MsgConstant.RET_CHARGE_ADD_FAILURE));
	  }else{
		  
		// Create new charge entity
		Charge chargeEntity = new Charge();
		
		// copy all user inputs to the new charge entity
		BeanUtils.copyProperties(chargeInput, chargeEntity);
		
		String chargeId = IdWorker.get32UUID();									   // 设置收费项目ID
		chargeEntity.setId(chargeId);
					
		if (chargeService.insert(chargeEntity)) {
			
			int cfNexusItem = Integer.MIN_VALUE;									// 关联项[住房：0,住房租赁：1]-车位的编号[车位：2,车位租赁：3]
			cfNexusItem = chargeEntity.getCfNexusItem();
			
			List<String> regions = chargeEntity.getRegionCode();					// 获取区域List编号
			
			if(0 == cfNexusItem || 1 == cfNexusItem) {
				
				List<House> houses = houseService.getListHousesByRegionCode(regions);// 根据区域编号获取区域内所有住房
				
				ChargeItemDetail chargeItemDetail = null;							// 实例化个人收费项目
				for (House house : houses) {
					
					HouseOwner houseOwner = houseOwnerService.getHouseOwnerByHouseID(house.getId());// 根据住房编号，获取房主信息
					
					if(null == houseOwner) continue;
					
					chargeItemDetail = new ChargeItemDetail();
					chargeItemDetail.setId(IdWorker.get32UUID());
					chargeItemDetail.setDetailCode("aguyue_");						// 收费编号待确认生成方式
					chargeItemDetail.setRelatedId(house.getId());					// 关联房屋id
					chargeItemDetail.setRelatedObject("house");						// 关联类型
					chargeItemDetail.setStatus("not pay");							// 交费状态
					chargeItemDetail.setDetailPayer(houseOwner.getId());			// 交费人id
					
					chargeItemDetailService.insert(chargeItemDetail);				// 插入到数据库
				}
				
				
			}else if(2 == cfNexusItem || 3 == cfNexusItem) {
				
				List<Park> parks = parkService.getListParksByRegionCode(regions);											// 根据区域编号获取区域内所有车位
				
				ChargeItemDetail chargeItemDetail = null;							// 实例化个人收费项目
				
				for(Park park : parks) {
					
					HouseOwner houseOwner = houseOwnerService.getHouseOwnerByParkID(park.getId());								// 根据车位编号，获取房主信息
					
					if(null == houseOwner) continue;
					
					chargeItemDetail = new ChargeItemDetail();
					chargeItemDetail.setId(IdWorker.get32UUID());
					chargeItemDetail.setDetailCode("aguyue_");						// 收费编号待确认生成方式
					chargeItemDetail.setRelatedId(park.getId());					// 关联房屋id
					chargeItemDetail.setRelatedObject("park");						// 关联类型
					chargeItemDetail.setStatus("not pay");							// 交费状态
					chargeItemDetail.setDetailPayer(houseOwner.getId());			// 交费人id
					
					chargeItemDetailService.insert(chargeItemDetail);					// 插入到数据库
				}
				
			}else {
				
			}
			
			entity.setRetCode(CommonConstant.RESULT_CODE_OK);
			entity.setRetMessage(getMessage(MsgConstant.RET_CHARGE_ADD_SUCCESS));
		}else {
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_IMPLEMENTED, 
					getMessage(MsgConstant.RET_CHARGE_ADD_FAILURE));
		}
		// Insert the charge entity into the database
		chargeService.insert(chargeEntity);
					
		//Return message and HTTP result code
		entity.setRetCode(CommonConstant.RESULT_CODE_OK);
		entity.setRetMessage(getMessage(MsgConstant.RET_CHARGE_ADD_SUCCESS));
	  }
		
		return entity;
	}
	
	
	/** 
	 * update the existing Charge
	 * 
	 * 1. Check if all required field are filled in.
	 * 2. Check if all the inputs are valid.
	 * 3. update the Charge in the DB.
	 * 
	 *@param 
	 *@author jess
	 *return 
	 *
	 **/
	@ApiOperation("The charge settings page, click the update button, update charge")
	@RequestMapping(value = "/", method = RequestMethod.PUT)
	public RetEntity updateCharge(@RequestBody ChargeInput chargeInput) throws Exception{
		
         RetEntity entity = new RetEntity();
		
		// update the charge entity in the database
		// Create new charge entity
		Charge chargeEntity = new Charge();
		// copy all user inputs to the new charge entity
		BeanUtils.copyProperties(chargeInput, chargeEntity);
		
		chargeService.updateById(chargeEntity);
		
		//Return message and HTTP result code
		entity.setRetCode(CommonConstant.RESULT_CODE_OK);
		entity.setRetMessage(getMessage(MsgConstant.RET_CHARGE_UPDATE_SUCCESS));
		 
		
		return null;
	}
	
	
	/** 
	 * delete the existing Charge
	 * 1. Check if the corresponding Id exists in the DB.
	 * 2. Delete the Charge from the DB.
	 * 
	 *@param  id
	 *@author jess
	 *return 
	 *
	 **/
	@ApiOperation("The charge settings page, click the delete button, delete charge")
	@RequestMapping(value="/id/{id}",method=RequestMethod.DELETE)
	public RetEntity delChargeById(@PathVariable("id") String id) throws Exception{

		RetEntity entity = new RetEntity();
		
		chargeService.deleteById(id);
		
		entity.setRetCode(CommonConstant.RESULT_CODE_OK);
		entity.setRetMessage(getMessage(MsgConstant.RET_CHARGE_DELETE_SUCCESS));
		return entity;
		
	}
}
